<template>
  <div class="new-cangku-container">
    <!-- 顶部操作栏 -->
    <div class="header-section">
      <div class="toolbar-right">
        <el-button type="primary" @click="handleAdd" style="background-color: #ff4d4f; border-color: #ff4d4f;">
          <el-icon><Plus /></el-icon>
          新建
        </el-button>
        <el-button type="default" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
                <el-button type="default" @click=" handleBatchDelete">
          <el-icon></el-icon>
          删除
        </el-button>
       
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-item">
        <label>仓库编码：</label>
        <el-input v-model="searchForm.cangkuNo" placeholder="请输入仓库编码" style="width: 200px" />
      </div>
      <div class="search-item">
        <label>仓库名称：</label>
        <el-input v-model="searchForm.cangName" placeholder="请输入仓库名称" style="width: 200px" />
      </div>
      <el-button type="primary" @click="getCangKuList" style="margin-left: 20px;">查询</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        :data="cangkuList"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
       <el-table-column prop="cangNo" label="编码" min-width="120" />
        <el-table-column prop="cangKuName" label="名称" min-width="150" />
        <el-table-column prop="bm" label="所属仓库" min-width="120" />
         <el-table-column prop="cangName" label="所属仓库名称" min-width="120" />
        <el-table-column prop="mShu" label="描述" min-width="150" />
        <el-table-column prop="createName" label="创建人" min-width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ scope.row.createTime ? moment(scope.row.createTime).format('YYYY-MM-DD') : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ scope.row.updateTime ? moment(scope.row.updateTime).format('YYYY-MM-DD') : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="text" class="action-btn" @click="handleEdit(row)" title="编辑">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="text" class="action-btn delete-btn" @click="handleSingleDelete(row)" title="删除">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <div class="pagination-info">共 {{ pagination.totalCount }} 条数据</div>
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, sizes, jumper"
          :total="pagination.totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="cangkuFormRef"
        :model="formData"
        label-width="120px"
      >
        <el-form-item label="库位编码" >
          <el-input v-model="formData.cangNo" placeholder="库位编码" />
        </el-form-item>
        <el-form-item label="库位名称" >
          <el-input v-model="formData.cangKuName" placeholder="请输入库位名称" />
        </el-form-item>
        <el-form-item label="所属仓库" prop="cangName">
           <el-select v-model="formData.bm" placeholder="请选择所属仓库" style="width: 100%" @change="handleCangkuChange">
            <el-option
              v-for="item in cangkuOptions"
              :label="`${item.cangkuNo} | ${item.cangName}`"
              :value="item.cangkuNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="mShu">
          <el-input v-model="formData.mShu" placeholder="请输入描述" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { APIs } from '../../Http/http'
import { Edit, Delete, Plus, Download } from '@element-plus/icons-vue'
import moment from 'moment'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

// 表格数据
const cangkuList = ref<any[]>([])
// 仓库下拉框选项
const cangkuOptions = ref<any[]>([])
// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新建仓库')
const cangkuFormRef = ref()

// 搜索表单
const searchForm = reactive({
  cangkuNo: '',
  cangName: ''
})

// 选中的行数据
const selectedRows = ref<any[]>([])

// 表单数据
const formData = reactive({
  "cangKuName": "",
  "cangNo": "",
  "bm": "",
  "cangName": "",
  "mShu": "",
  "createName": ""
})
onMounted(() => {
  getCangKuList()
  getCangkuOptions()
})
const getCangKuList = async () => {
   {
    const response = await APIs.get('/api/Read/GetCangKuQU', {
      params: {
        PageIndex: pagination.pageIndex,
        PageSize: pagination.pageSize,
        ...searchForm
      }
    })
    
    if (response.data.code === 100) {
      cangkuList.value = response.data.data.data
      pagination.totalCount = response.data.data.totalCount
    }
  }
}

// 获取仓库下拉框选项
const getCangkuOptions = async () => {
  try {
    const response = await APIs.get('/api/Read/GetCangku')
    if (response.data && response.data.code === 100) {
      cangkuOptions.value = response.data.data
    }
  } catch (error) {
    console.error('获取仓库选项失败:', error)
    ElMessage.error('获取仓库选项失败')
  }
}

// 处理所属仓库选择变化，自动填充仓库名称
const handleCangkuChange = (value: string) => {
  // 根据选择的仓库编码查找对应的仓库选项
  const selectedOption = cangkuOptions.value.find(item => item.cangkuNo === value)
  if (selectedOption) {
    // 自动填充仓库名称
    formData.cangName = selectedOption.cangName
  }
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新建仓库'
  // 重置表单数据
  Object.assign(formData, {
    "cangKuName": "",
    "cangNo": "",
    "bm": "",
    "cangName": "",
    "mShu": "",
    "createName": ""
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑仓库'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 单个删除
const handleSingleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除仓库 "${row.cangName}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    APIs.post('/api/Write/DeleteKuqu',row).then(() => {
      ElMessage.success('删除成功')
      getCangKuList()
    })
  })
}
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
  console.log(selectedRows.value);
};
const getSelectedRowsArray = () => {
  return selectedRows.value.map(row => ({
    id: row.cangKuId,
  }));
};

// 实现批量删除功能
const handleBatchDelete = () => {
  const selectedIds = getSelectedRowsArray();
  const requestData = {
    Ids: selectedIds.map(item => item.id)
  };
  
  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}个车间吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    APIs.post("/api/Write/PDeleKuqu", requestData).then(res=>{
      if(res.data.code==100) {
        ElMessage.success("批量删除成功");
        getCangKuList();
      }
    })
  });
};
// 保存表单
const handleSave = () => {
  if (!cangkuFormRef.value) return
  
  cangkuFormRef.value.validate().then(() => {
    const submitData = {
      ...formData
    }
    console.log(formData)
    if (dialogTitle.value === '编辑仓库') {
      APIs.post('/api/Write/UpdateKuqu', submitData).then(response => {
        if (response.data.code === 100) {
          ElMessage.success('更新成功')
          dialogVisible.value = false
          getCangKuList()
        } else {
          ElMessage.error('更新失败')
        }
      })
    } else {
      APIs.post('/api/Write/AddKuqu', submitData).then(response => {
        if (response.data.code === 100) {
          ElMessage.success('新增成功')
          dialogVisible.value = false
          getCangKuList()
        } else {
          ElMessage.error('新增失败')
        }
      })
    }
  })
}

const handleExport = () => {
  if (cangkuList.value.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }

  try {
    // 准备导出数据
    const exportData = cangkuList.value.map((row, index) => ({
      '序号': index + 1,
      '编码': row.cangNo,
      '名称': row.cangName,
      '仓库编码': row.bm,
      '仓库名称': row.cangName,
      '描述': row.mShu,
      '创建人': row.createName,
      '创建时间': moment(row.createTime).format('YYYY-MM-DD'),
      '更新时间': moment(row.updateTime).format('YYYY-MM-DD')
    }))

    // 创建工作簿
    const worksheet = XLSX.utils.json_to_sheet(exportData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '仓库数据')

    // 设置列宽
    const colWidths = [
      { wch: 8 },  // 序号
      { wch: 15 }, // 编码
      { wch: 20 }, // 名称
      { wch: 15 }, // 仓库编码
      { wch: 20 }, // 仓库名称
      { wch: 30 }, // 描述
      { wch: 12 }, // 创建人
      { wch: 15 }, // 创建时间
      { wch: 15 }  // 更新时间
    ]
    worksheet['!cols'] = colWidths

    // 生成Excel文件
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
    const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    
    // 生成文件名（包含当前时间）
    const now = new Date()
    const timestamp = now.getFullYear() + 
      String(now.getMonth() + 1).padStart(2, '0') + 
      String(now.getDate()).padStart(2, '0') + '_' +
      String(now.getHours()).padStart(2, '0') + 
      String(now.getMinutes()).padStart(2, '0') + 
      String(now.getSeconds()).padStart(2, '0')
    
    const filename = `仓库数据_${timestamp}.xlsx`
    
    // 下载文件
    saveAs(data, filename)
    
    ElMessage.success(`成功导出 ${cangkuList.value.length} 条数据`)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}
const handleDialogClose = () => {
  if (cangkuFormRef.value) {
    cangkuFormRef.value.resetFields()
  }
  dialogVisible.value = false
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  getCangKuList()
}

const handleCurrentChange = (current: number) => {
  pagination.pageIndex = current
  getCangKuList()
}
</script>

<style scoped>
.new-cangku-container {
  background: white;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 15px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #e4e7ed;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

.search-section {
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-section {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.action-btn {
  color: #409eff;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #ff8585;
}
</style>